package com.pucheng.bracelet.ui.activity.clock

import android.os.Bundle
import android.view.KeyEvent
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.observe
import androidx.recyclerview.widget.LinearLayoutManager
import com.pucheng.bracelet.R
import com.pucheng.bracelet.databinding.ActivityClockBinding
import com.pucheng.bracelet.ui.adapter.ClockAdapter
import com.pucheng.bracelet.ui.adapter.ClockData
import com.pucheng.bracelet.viewmodel.clock.ClockViewModel
import kotlinx.android.synthetic.main.layout_title.*
import me.hgj.jetpackmvvm.base.activity.BaseVmDbActivity

class ClockActivity : BaseVmDbActivity<ClockViewModel, ActivityClockBinding>() {
    private var fragment: ClockEditFragment? = null
    private val mAdapter = ClockAdapter(
        { index: Int, clockData: ClockData ->
            mViewModel.selectData(index, clockData)
        },
        { index: Int, clockData: ClockData ->
            fragment = ClockEditFragment.newInstance(index, clockData) {
                supportFragmentManager.beginTransaction().apply {
                    fragment?.let {
                        hide(it)
                        commit()
                    }
                }
            }
            supportFragmentManager.beginTransaction().apply {
                fragment?.let {
                    replace(R.id.fl_clock_edit, it)
                    commit()
                }
            }
        })
    private lateinit var mClockViewModel: ClockViewModel
    override fun layoutId(): Int = R.layout.activity_clock

    override fun initView(savedInstanceState: Bundle?) {
        mClockViewModel = ViewModelProvider(this).get(ClockViewModel::class.java)
        mDatabind.apply {
            viewModel = mClockViewModel
            lifecycleOwner = this@ClockActivity
            rvPush.apply {
                adapter = mAdapter
                layoutManager = LinearLayoutManager(this@ClockActivity)
            }
            ibtn_back.apply {
                setOnClickListener {
                    mViewModel.setClockDataToBle()
                    finish()
                }
            }
            tv_title.apply {
                text = "日常闹钟"
            }
        }
        mViewModel.apply {
            clockData.observe(this@ClockActivity) {
                mAdapter.submitList(it)
                mAdapter.notifyDataSetChanged()
            }
//            editClockData.observe(this@ClockActivity) {
//                mAdapter.notifyDataSetChanged()
//            }
        }
    }

    override fun createObserver() {
    }

    override fun dismissLoading() {
    }

    override fun showLoading(message: String) {

    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK){
            mViewModel.setClockDataToBle()
        }
        return super.onKeyDown(keyCode, event)
    }

}